<template>
  <div>
    <el-container>
      <el-main>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12">
            <el-card shadow="hover" class="card">
              <h2>Prediction Case Display</h2>
              <div style="text-align: left;padding: 0 40px;margin-bottom: 40px">
                <p><strong>Disease:</strong><br>
                  Coccidiosis in chickens; Coccidiosis in ducks; Bovine coccidiosis; Ovine and caprine coccidiosis; Rabbit coccidiosis; Swine coccidiosis.
                </p>
                <p><strong>Drug:</strong><br>
                  Erythromycin; Pyrimethamine; Azithromycin; Dapsone; Doxycycline; Sulfadiazine; Trimethoprim; Nitazoxanide; Albendazole.
                </p>
                <p>Here is the download link for the sample file. You can download the sample file and submit a prediction, or you can upload a CSV file with the first column labeled 'disease_name' and the second column labeled 'drug_name' to submit a prediction task. After a short wait, the prediction results will appear in the Results section, and any parasitic disease and drug combinations that cannot be predicted will be displayed in the Log Data section. This process usually does not take long. Please note that APDAP can only recognize the English names of parasitic diseases and drugs.</p>
              </div>
              <el-button type="primary" style="background-color: #004488;" @click="downloadExample">Download the Example</el-button>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-card shadow="hover" class="card">
              <h2>Submit Prediction Data</h2>
              <el-form :model="form" :rules="rules" ref="form" label-width="120px" class="custom-form">
                <el-form-item label="User Name" prop="username">
                  <el-input v-model="form.username"></el-input>
                </el-form-item>
                <el-form-item label="User Email" prop="email">
                  <el-input v-model="form.email"></el-input>
                </el-form-item>
                <el-form-item label="Upload File" prop="filePath">
                  <el-upload
                      action="/api/upload_file"
                      class="upload-demo"
                      drag
                      :on-success="handleFileSuccess"
                      :before-upload="beforeUpload"
                      :file-list="fileList"
                      :limit="1"
                      :auto-upload="true">
                    <i class="el-icon-upload" style="color: #004488;"></i>
                    <div class="el-upload__text">Drag the file here, or click to upload</div>
                    <div class="el-upload__tip" slot="tip">Only CSV files are allowed</div>
                  </el-upload>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" style="background-color: #004488;" @click="handleSubmit">Submit</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>
        </el-row>

        <el-collapse v-model="activeNames" accordion v-if="showRes">
          <el-collapse-item title="Log Data" name="log">
            <template slot="title">
              <el-badge is-dot class="item" ></el-badge>
              <span class="collapse-title">Log Data</span>
            </template>
            <pre class="log-data">{{ logMessages.join('\n') }}</pre>
          </el-collapse-item>
          <el-collapse-item title="Table Data" name="table">
            <template slot="title">
              <el-badge is-dot class="item" ></el-badge>
              <span class="collapse-title">Result</span>
            </template>
            <el-table :data="tableData" style="width: 100%" :empty-text="'No data available'">
              <el-table-column prop="disease_name" label="Disease Name"></el-table-column>
              <el-table-column prop="drug_name" label="Drug Name"></el-table-column>
              <el-table-column prop="y_prob" label="Probability"></el-table-column>
            </el-table>
          </el-collapse-item>
        </el-collapse>
      </el-main>
    </el-container>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        username: '',
        email: '',
        filePath: ''
      },
      fileList: [],
      rules: {
        username: [
          {required: true, message: 'Please enter your username', trigger: 'blur'}
        ],
        email: [
          {required: true, message: 'Please enter your email', trigger: 'blur'},
          {type: 'email', message: 'Please enter a valid email address', trigger: ['blur', 'change']}
        ],
        filePath: [
          {required: true, message: 'Please upload a file', trigger: 'change'}
        ]
      },
      activeNames: [],
      logMessages: [],
      tableData: [],
      showRes: false
    };
  },
  methods: {
    async downloadExample() {
      try {
        const response = await fetch(`/api/downloadExample`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          },
        });

        if (!response.ok) {
          throw new Error('Download example file failed');
        }

        const blob = await response.blob();
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'sample.csv';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (error) {
        this.$message.error(error.message);
      }
    },
    handleFileSuccess(response, file, fileList) {
      if (response.file_path) {
        this.form.filePath = response.file_path;
        this.fileList = [file];
        this.$message.success('Upload success');
      } else {
        this.$message.error('Upload failed');
      }
    },
    handleSubmit() {
      const startTime = Date.now();
      const loading = this.$loading({
        lock: true,
        text: `Waiting for your predict result. Time: 0s`,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      const updateTimer = () => {
        const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
        loading.setText(`Waiting for your predict result. Time: ${elapsedTime}s`);
      };
      const timerInterval = setInterval(updateTimer, 1000);

      this.$refs.form.validate((valid) => {
        if (valid) {
          fetch('/api/submit_form', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(this.form)
          })
              .then(response => response.json())
              .then(data => {
                if (data.tableData) {
                  this.tableData = data.tableData;
                  this.logMessages = data.logMessages;
                  this.activeNames = ["table"];
                  loading.close();
                  clearInterval(timerInterval);
                  this.showRes = true;
                  this.$message.success("Prediction Data success");
                } else {
                  this.showRes = true;
                  this.logMessages = data.logMessages;
                  loading.close();
                  clearInterval(timerInterval);
                  this.$message.error('Form submission failed');
                }
              })
              .catch(error => {
                console.error('Error:', error);
                loading.close();
                clearInterval(timerInterval);
                this.$message.error('Form submission failed');
              });
        } else {
          console.log('Form validation failed');
          return false;
        }
      });
    },
    beforeUpload(file) {
      const isCSV = file.type === 'text/csv';
      if (!isCSV) {
        this.$message.error('Only CSV files are allowed!');
      }
      return isCSV;
    }
  }
};
</script>

<style scoped>
.custom-form .el-form-item__label {
  white-space: nowrap;
  word-break: keep-all;
}

.content {
  text-align: left;
  padding: 0 40px;
  margin-bottom: 40px;
}

.collapse-title {
  font-size: 18px;
  font-weight: bold;
}

.log-data {
  font-size: 14px;
  white-space: pre-wrap;
}

.el-upload__text {
  color: #004488;
}

.el-upload__tip {
  color: #004488;
}

.el-button--primary {
  background-color: #004488;
  border-color: #004488;
}
</style>
